﻿#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDateTime>
#include <QJsonArray>
#include <QJsonValue>
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , udp_sender(this)
    , udp_receiver(this)
{
    ui->setupUi(this);
    is_connected = false;
    connect(ui->connectButton, &QPushButton::clicked, this, &MainWindow::clickConnectButton);
    connect(ui->radioButton_s, &QRadioButton::clicked, this, &MainWindow::chooseStandbyMode);
    connect(ui->radioButton_n, &QRadioButton::clicked, this, &MainWindow::chooseNavigationMode);
    connect(ui->radioButton_m, &QRadioButton::clicked, this, &MainWindow::chooseManualMode);
    connect(ui->sendButton, &QPushButton::clicked, this, &MainWindow::clickSendButton);
    connect(ui->pauseButton, &QPushButton::clicked, this, [=](){clickControlButton(2);});
    connect(ui->resumeButton, &QPushButton::clicked, this, [=](){clickControlButton(1);});
    connect(ui->endButton, &QPushButton::clicked, this, [=](){clickControlButton(3);});
    connect(ui->actionButton, &QPushButton::clicked, this, &MainWindow::clickActionButton);
    connect(ui->horizontalSlider, &QSlider::valueChanged, this, &MainWindow::setArg);
    connect(ui->comboBox_action, &QComboBox::currentTextChanged, this, [=](){
        if(ui->comboBox_action->currentIndex()>9)
            ui->horizontalSlider->setEnabled(true);
        else
            ui->horizontalSlider->setEnabled(false);
    });
    send_json_object.insert("timestamp", 0);
    send_json_object.insert("msg_id", 201);
    send_json_object.insert("run_mode", 0);
    ui->lineEdit_arg->setText("0");
    ui->horizontalSlider->setEnabled(false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::clickConnectButton()
{
    if(!is_connected) {
        QString aim_ip = ui->lineEdit_ip->text();
        int aim_port = ui->spinBox_aim_port->value();
        int local_port = ui->spinBox_local_port->value();
        if(udp_sender.setIpAndPort(aim_ip, aim_port) && udp_receiver.setPort(local_port)) {
            connected();
        }
    } else {
        disconnected();
    }
}

void MainWindow::connected()
{
    is_connected = true;
    ui->connectButton->setText(QString::fromLocal8Bit("断开"));
    ui->groupBox_2->setEnabled(true);
    connect(&udp_receiver, &UdpReceiver::receiveJson, this, &MainWindow::updataTreeWidget);
}

void MainWindow::disconnected()
{
    is_connected = false;
    ui->connectButton->setText(QString::fromLocal8Bit("连接"));
    ui->groupBox_2->setEnabled(false);
    ui->groupBox_3->setEnabled(false);
    ui->groupBox_4->setEnabled(false);
    ui->radioButton_s->setChecked(true);
    send_json_object["run_mode"] = 0;
    udp_receiver.breakLink();
    disconnect(&udp_receiver, &UdpReceiver::receiveJson, this, &MainWindow::updataTreeWidget);
}

void MainWindow::chooseStandbyMode()
{
    send_json_object["run_mode"] = 0;
    ui->groupBox_3->setEnabled(false);
    ui->groupBox_4->setEnabled(false);
}

void MainWindow::chooseNavigationMode()
{
    send_json_object["run_mode"] = 2;
    QJsonObject targetObject;
    targetObject.insert("timestamp", 0);
    nav_object.insert("target", targetObject);
    send_json_object["nav"] = nav_object;
    ui->groupBox_3->setEnabled(true);
    ui->groupBox_4->setEnabled(false);
}

void MainWindow::chooseManualMode()
{
    send_json_object["run_mode"] = 1;
    ui->groupBox_3->setEnabled(false);
    ui->groupBox_4->setEnabled(true);
}

void MainWindow::clickSendButton()
{
    navigationJson();
}

void MainWindow::navigationJson()
{
    QDateTime dateTime = QDateTime::currentDateTime();
    QJsonObject target_object;
    target_object.insert("timestamp", dateTime.toMSecsSinceEpoch());
    target_object.insert("nid", ui->spinBox_nid->value());
    if(!ui->lineEdit_x->text().isEmpty() && !ui->lineEdit_y->text().isEmpty()) {
        QJsonArray coordArray;
        coordArray.append(ui->lineEdit_x->text().toDouble());
        coordArray.append(ui->lineEdit_y->text().toDouble());
        target_object.insert("coord", coordArray);
    }
    nav_object.insert("target", target_object);
    nav_object["state"] = 1;
    send_json_object["nav"] = nav_object;
}

void MainWindow::clickControlButton(int control_id)
{
    nav_object["state"] = control_id;
    send_json_object["nav"] = nav_object;
}

void MainWindow::updataTreeWidget(QJsonObject data)
{
    QJsonValue root = data;
    ui->treeWidget->topLevelItem(0)->setText(1, QString::number(root["timestamp"].toDouble(), 'f', 0));
    ui->treeWidget->topLevelItem(1)->setText(1, root["nav"]["map"].toString());
    ui->treeWidget->topLevelItem(2)->setText(1, QString("%1").arg(root["pose"]["xyz"][0].toDouble()));
    ui->treeWidget->topLevelItem(3)->setText(1, QString("%1").arg(root["pose"]["xyz"][1].toDouble()));
    ui->treeWidget->topLevelItem(4)->setText(1, QString("%1").arg(root["pose"]["rpy"][2].toDouble()));
    ui->treeWidget->topLevelItem(5)->setText(1, QString("%1").arg(root["vel"].toDouble()));
    ui->treeWidget->topLevelItem(6)->setText(1, QString("%1").arg(root["battery"]["capacity"].toDouble()));
    ui->treeWidget->topLevelItem(7)->setText(1, QString("%1").arg(root["battery"]["charging"].toBool()));
    ui->treeWidget->topLevelItem(8)->setText(1, QString("%1").arg(root["rtk"]["star"].toInt()));
    ui->treeWidget->topLevelItem(9)->setText(1, QString("%1").arg(root["nav"]["state"].toInt()));
    ui->treeWidget->topLevelItem(10)->setText(1, QString::number(root["nav"]["target"]["timestamp"].toDouble(), 'f', 0));
    ui->treeWidget->topLevelItem(11)->setText(1, QString("%1").arg(root["nav"]["target"]["nid"].toInt()));
    ui->treeWidget->topLevelItem(12)->setText(1, QString("%1").arg(root["nav"]["target"]["coord"][1].toDouble()));
    ui->treeWidget->topLevelItem(13)->setText(1, QString("%1").arg(root["nav"]["target"]["coord"][2].toDouble()));
    ui->treeWidget->topLevelItem(14)->setText(1, QString("%1").arg(root["nav"]["target"]["state"].toInt()));
}

void MainWindow::sendMsg()
{
    if(is_connected) {
        QDateTime dateTime = QDateTime::currentDateTime();
        send_json_object["timestamp"] = dateTime.toMSecsSinceEpoch();
        udp_sender.sendJson(send_json_object);
    }
}

void MainWindow::clickActionButton()
{
    QString func[] = {"StandUp", "LieDown", "Realse", "MarkTimeOn", "MarkTimeOff", "LightStep",
                      "HeavyStep", "CrawlOn", "CrawlOff", "EmergencyStop", "Forward", "Backward",
                      "LeftSideWalk", "RightSideWalk", "TurnLeft", "TurnRight"};
    QJsonObject action_object;
    action_object.insert("name", func[ui->comboBox_action->currentIndex()]);
    if(ui->comboBox_action->currentIndex() > 9) {
        QJsonArray args_array;
        args_array.append(ui->lineEdit_arg->text().toDouble());
        action_object.insert("args", args_array);
    }
    send_json_object.insert("action", action_object);
}

void MainWindow::setArg(int x)
{
    ui->lineEdit_arg->setText(QString("%1").arg((double)x/200));
}
